package com.woniuxy.predicate;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * @Author: 杨俊杰
 * @Description: TODO
 * @DateTime: 22/12/08/0008 16:26
 * @Component: 成都蜗牛学苑
 **/
@Component
public class OidAndNumlimitRoutePredicateFactory extends AbstractRoutePredicateFactory<OidAndNumlimitRoutePredicateFactory.Config> {
    public OidAndNumlimitRoutePredicateFactory() {
        //确保抛出的是PidlimitRoutePredicateFactory里面的Config的class对象
        super(Config.class);
    }
    /**
     * - Pidlimit=1,3  需要截取1赋值给minPid，3赋值给maxPid
     * ChangeLog : 1. 创建 (22/12/08/0008 16:44 [马宇航]);
     *
     * @return java.util.List<java.lang.String>
    */
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("minOid","maxOid","minNum","maxNum");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                String path = serverWebExchange.getRequest().getURI().getPath();
                String[] split = path.split("/");
                String pidString = split[split.length - 2];
                String numString = split[split.length - 1];
                int pid = Integer.parseInt(pidString);
                int num=Integer.parseInt(numString);
                if(config.getMinOid()<=pid&&pid<=config.getMaxOid()){
                    if(config.getMinNum()<=num&&num<=config.getMaxNum()){
                        return true;
                    }else
                        return false;
                }else {
                    return false;
                }
            }
        };
    }

    /**
    * @Author: 杨俊杰
    * @Todo: 静态内部类：它和 写外面是一样的！
    * @DateTime:  22/12/08/0008 16:28
    * @Component: 成都蜗牛学苑
    **/
    public static class Config{
        int minOid;
        int maxOid;
        int minNum;
        int maxNum;

        public void setMinOid(int minOid) {
            this.minOid = minOid;
        }

        public void setMaxOid(int maxOid) {
            this.maxOid = maxOid;
        }

        public void setMinNum(int minNum) {
            this.minNum = minNum;
        }

        public void setMaxNum(int maxNum) {
            this.maxNum = maxNum;
        }

        public int getMinOid() {
            return minOid;
        }

        public int getMaxOid() {
            return maxOid;
        }

        public int getMinNum() {
            return minNum;
        }

        public int getMaxNum() {
            return maxNum;
        }
    }
}
